//
//  OtherNetworking.m
//  智云网校
//
//  Created by Damon on 2017/6/8.
//  Copyright © 2017年 bwx. All rights reserved.
//

#import "OtherNetworking.h"
#import "AppUtils.h"
#import "DUserDefault.h"
#import "DUserDefault.h"
//#import "JANALYTICSEventObject.h"
//#import "JANALYTICSService.h"

//static NSString *const RESPONSE_CODE        = @"code";


@interface OtherNetworking ()
{
    
    // 下载句柄
    NSURLSessionDownloadTask *_downloadTask;
    
}

@end

@implementation OtherNetworking


static OtherNetworking *manager = nil;
static dispatch_once_t onceToken;

+ (OtherNetworking *)sharedManager {
    dispatch_once(&onceToken, ^{
        manager = [[OtherNetworking alloc] init];
    });
    return manager;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (NSString *)STRURL{
    if ([SettingObject objectIsValid:_STRURL]) {
        return _STRURL;
    }else{
        NSString *_strurl = [DUserDefault getDataObjectForKey:USERDERAULT_STRURL];
        if (![SettingObject objectIsValid:_strurl]) {
            _strurl = nil;
        }

        _STRURL = _strurl ? : @"http://zby.huahualive.net";
        

        return _STRURL;
    }
}
- (NSString *)STRURLIMG{
    if ([SettingObject objectIsValid:_STRURLIMG]) {
        return _STRURLIMG;
    }else{
        NSString *_strurlimg = [DUserDefault getDataObjectForKey:USERDERAULT_STRURLIMG];
        if (![SettingObject objectIsValid:_strurlimg]) {
            _strurlimg = nil;
        }

        _STRURLIMG = _strurlimg ? : @"http://zby.huahualive.net";
        

        return _STRURLIMG;

    }
}

-(void)isWIFI{
    AFNetworkReachabilityManager *managerReachability = [AFNetworkReachabilityManager sharedManager];
    //要监控网络连接状态，必须要先调用单例的startMonitoring方法
    [managerReachability startMonitoring];
    [managerReachability setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"%ld", (long)status);
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
                break;
            default:
                break;
        }
    }];
}

- (void)downloadTaskWithRequest:(NSString  *)filepath
                       progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlockDD
                       fileName:(NSString *)fileName
                           type:(DownloadFileType)type
              completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandlerDD{
    
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    // 1. 创建会话管理者
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    // 2. 创建下载路径和请求对象
    NSURL *URL = [NSURL URLWithString:filepath];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    // 3.创建下载任务
    /**
     * 第一个参数 - request：请求对象
     * 第二个参数 - progress：下载进度block
     *      其中： downloadProgress.completedUnitCount：已经完成的大小
     *            downloadProgress.totalUnitCount：文件的总大小
     * 第三个参数 - destination：自动完成文件剪切操作
     *      其中： 返回值:该文件应该被剪切到哪里
     *            targetPath：临时路径 tmp NSURL
     *            response：响应头
     * 第四个参数 - completionHandler：下载完成回调
     *      其中： filePath：真实路径 == 第三个参数的返回值
     *            error:错误信息
     */
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) {
        
        
        NSLog(@"---进度:%@",[NSString stringWithFormat:@"当前下载进度:%.2f%%",100.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount]);
        downloadProgressBlockDD(downloadProgress);
        
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        NSString *urlppp = response.URL.absoluteString;
        NSArray  *array = [urlppp componentsSeparatedByString:@"."];
        if ([SettingObject objectIsValid:array]) {
            urlppp = array.lastObject;
        }else{
            urlppp = @"";
        }
        NSURL *filePath;
        switch (type) {
            case DownloadFileTypeOutline:
                filePath = [FileManagerUtil getDirectoryAtOutline];
                break;
            case DownloadFileTypeTalkfun:
                filePath = [FileManagerUtil getDirectoryAtTalkfun];
                break;
            case DownloadFileTypeCCPlayer:
                filePath = [FileManagerUtil getDirectoryAtCCPlayer];
                break;
            case DownloadFileTypeSLPG:
                filePath = [FileManagerUtil getDirectoryAtSLPG];
                break;
            default:
                break;
        }
        
        filePath = [filePath URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",fileName,urlppp]];
        return filePath;
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        completionHandlerDD(response,filePath,error);
    }];
    
    // 4. 开启下载任务
    [downloadTask resume];
}
- (void)stopDownload{
    //暂停下载
    [_downloadTask suspend];
}
- (void)startDownload{
    //开始下载
    [_downloadTask resume];
}


- (void)verifyItunesAppVersionCompletion:(void (^)())completion{
    NSString *_strurl = [DUserDefault getDataObjectForKey:USERDERAULT_STRURL];
    if ([SettingObject objectIsValid:_strurl] &&
        [_strurl rangeOfString:@"iosapp"].location == NSNotFound) {
        
        completion();

    }else{
        
        NSString *urlStr = [NSString stringWithFormat:@"http://www.xiaomaigongkao.com/AppApi/Member/version"];
        
#if TGT_XBGK
        urlStr = [NSString stringWithFormat:@"http://www.xuebagk.com/AppApi/Member/version"];
#endif
        
        NSDictionary *Params = @{@"bundleId":[AppUtils getBundleID],
                                 @"version":[AppUtils getLocalAppVersion]};
        SGParameter *parameter = [[SGParameter alloc] init];
//        parameter.body.data = Params;
        [SGHttpTool POST:urlStr parameter:parameter sucess:^(id result) {
            NSDictionary * responseDict = (NSDictionary *)result;
            NSNumber * resCode = responseDict[RESPONSE_CODE];
            
            
            //智云网校 api
    #if TGT_ZYWX

            if (resCode.integerValue == 2000) {//成功 微信支付宝支付
                self.isInAppPurchase = NO;
                //智云网校 api
                self.STRURL = @"http://demo.zhiyun88.com/AppApi/";
                self.STRURLIMG = @"http://demo.zhiyun88.com";

            }else{//失败 //内购
                //智云网校内购 api
                self.isInAppPurchase = YES;
                self.STRURL = @"http://iosapp.zhiyun88.com/AppApi/";
                self.STRURLIMG = @"http://iosapp.zhiyun88.com";
            }

            //小麦公考 api
    #elif TGT_XMGK

            if (resCode.integerValue == 2000) {//成功 微信支付宝支付
                self.isInAppPurchase = NO;
                self.STRURL = @"http://www.xiaomaigongkao.com/AppApi/";
                self.STRURLIMG = @"http://www.xiaomaigongkao.com";

            }else{//失败 //内购
                self.isInAppPurchase = YES;
                self.STRURL = @"http://iosapp.zhiyun88.com/AppApi/";
                self.STRURLIMG = @"http://iosapp.zhiyun88.com";
            }
            
            
            
            //学霸公考 api
    #elif TGT_XBGK
            
            NSLog(@"_________________%@",resCode);
            
            if (resCode.integerValue == 2000) {//成功 微信支付宝支付
                self.isInAppPurchase = NO;
                self.STRURL = @"http://www.xuebagk.com/AppApi/";
                self.STRURLIMG = @"http://www.xuebagk.com";

            }else{//失败 //内购
                self.isInAppPurchase = YES;
                self.STRURL = @"http://iosapp.zhiyun88.com/AppApi/";
                self.STRURLIMG = @"http://iosapp.zhiyun88.com";
//                self.isInAppPurchase = NO;
//                self.STRURL = @"http://www.xuebagk.com/AppApi/";
//                self.STRURLIMG = @"http://www.xuebagk.com";
                
            }
            
            
    #endif
        
            [DUserDefault setDataObject:self.STRURL forKey:USERDERAULT_STRURL];
            [DUserDefault setDataObject:self.STRURLIMG forKey:USERDERAULT_STRURLIMG];

            completion();

        } failure:^(id reslut) {
            completion();
        }];
        
    }
}

- (NSString *)kShareUrlCourseLive:(NSString *)courseID{
    return [NSString stringWithFormat:@"%@/Course/Center/details/course_id/%@",[OtherNetworking sharedManager].STRURLIMG,courseID];
}
- (NSString *)kShareUrlCourseRecorded:(NSString *)courseID{
    return [NSString stringWithFormat:@"%@/Course/Recorded/details/course_id/%@",[OtherNetworking sharedManager].STRURLIMG,courseID];
}
- (NSString *)kShareUrlCourseFace:(NSString *)courseID{
    return [NSString stringWithFormat:@"%@/Course/FaceCourse/facecourse_details/id/%@",[OtherNetworking sharedManager].STRURLIMG,courseID];
}
- (NSString *)kShareUrlCourseSLPG:(NSString *)courseID{
    return [NSString stringWithFormat:@"%@/Test/slpg_details/paper_id/%@",[OtherNetworking sharedManager].STRURLIMG,courseID];
}
- (NSString *)kShareUrlCourseBKZL:(NSString *)courseID{
    return [NSString stringWithFormat:@"%@/Article/article_details/id/%@",[OtherNetworking sharedManager].STRURLIMG,courseID];
}
- (NSString *)kShareUrlCourseQuestion:(NSString *)courseID{
    return [NSString stringWithFormat:@"%@/Question/question_share/ques_id/%@",[OtherNetworking sharedManager].STRURLIMG,courseID];
}
- (NSString *)kShareUrlCourseQuestionHistory:(NSString *)courseID{
    return [NSString stringWithFormat:@"%@/Question/paper_question_share/ques_id/%@",[OtherNetworking sharedManager].STRURLIMG,courseID];
}
- (NSString *)kShareUrlWholeAssessment{
    return [NSString stringWithFormat:@"%@/Question/paper_question_share/",[OtherNetworking sharedManager].STRURLIMG];
}

- (NSString *)AliPayCallbackAddress{
    return [NSString stringWithFormat:@"%@/Course/Alipay/app_notifyurl",[OtherNetworking sharedManager].STRURLIMG];
}
- (NSString *)WXPayCallbackAddress{
    return [NSString stringWithFormat:@"%@/Course/Wxapppay/notifyurl",[OtherNetworking sharedManager].STRURLIMG];
}


@end
